package com.zzy.controller;

import com.zzy.utils.W1;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
public class MyController
{
    @RequestMapping("/aa")
    public String getaa() throws Exception
    {
        W1 w1 = new W1();
        //链接zookeeper
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 10000, w1);
        w1.zk=zooKeeper;
        //查询子节点 开启触发监听器
        List<String> children = zooKeeper.getChildren("/server", true);
        if(children.size()==0 || children==null)
        {
            //没有开启的服务器,无处访问
            return "没有开启的服务器别访问了,歇着去吧！";
        }
        else
        {
            for (String p: children) {
                byte[] data = zooKeeper.getData("/server/"+p, true, null);
                //从子节点取值获得url
                String url = new String(data);
                try{
                    CloseableHttpClient client = HttpClients.createDefault();
                    HttpGet httpGet = new HttpGet(url+"/aa");
                    CloseableHttpResponse resp = client.execute(httpGet);
                    HttpEntity entity = resp.getEntity();
                    if(entity!=null)
                    {
                        //遍历子节点，能访问就结束
                        return "从服务器:"+url+"拿到了接口返回数据"+ EntityUtils.toString(entity);
                    }
                }catch (Exception e)
                {
                   System.out.println("请求"+url+"服务器失败，准备尝试请求其他服务器");
                }
            }
            return "应该是到不了这一步";
        }
    }
}
